#include "recboxitem.h"
#include "ui_recboxitem.h"

#include <QPropertyAnimation>

RecBoxItem::RecBoxItem(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::RecBoxItem)
{
    ui->setupUi(this);
    // 安装事件拦截器
    ui->musicImageBox->installEventFilter(this);
}

RecBoxItem::~RecBoxItem()
{
    delete ui;
}

// 原来实现鼠标进入或离开事件的图片动画效果
bool RecBoxItem::eventFilter(QObject *watched, QEvent *event)
{
    // 检查鼠标是否移动到图片上面
    if(watched == ui->musicImageBox)
    {
        int imageWidth = ui->musicImageBox->width();
        int imageHeight = ui->musicImageBox->height();
        // 拦截鼠标进入事件
        if(event->type() == QEvent::Enter) {
            QPropertyAnimation* animation = new QPropertyAnimation(ui->musicImageBox, "geometry");
            animation->setStartValue(QRect(9, 9, imageWidth, imageHeight));
            animation->setEndValue(QRect(9, 0, imageWidth, imageHeight));
            animation->start();

            // 动画结束时记得去销毁animation, 动画结束会触发finished信号
            connect(animation, &QPropertyAnimation::finished, this, [=]{
                delete animation;
                qDebug("图片上移动画结束");
            });
            return true;
        } else if(event->type() == QEvent::Leave) {
            // 拦截鼠标离开事件
            QPropertyAnimation* animation = new QPropertyAnimation(ui->musicImageBox, "geometry");
            animation->setStartValue(QRect(9, 0, imageWidth, imageHeight));
            animation->setEndValue(QRect(9, 9, imageWidth, imageHeight));
            animation->start();

            // 动画结束时记得去销毁animation, 动画结束会触发finished信号
            connect(animation, &QPropertyAnimation::finished, this, [=]{
                delete animation;
                qDebug("图片下移动画结束");
            });
            return true;
        }
    }
    // 如果不触发以上事件，去调用基类默认的事件拦截
    return QObject::eventFilter(watched, event);
}

void RecBoxItem::setText(const QString &text)
{
    ui->recBoxItemText->setText(text);
}

void RecBoxItem::setImage(const QString &imagePath)
{
    QString style = "background-image: url("+imagePath+")";
    ui->recMusicImage->setStyleSheet(style);
}
